package sing.core.util

import android.app.Activity
import android.content.Context
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

/**
 * 键盘相关
 */
object KeyBoardUtil {
    // 控制键盘显示 true为隐藏，false为显示
    fun hideInputMethod(activity: Activity, isHiden: Boolean) {
        val mInputMethodManager =
            activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (isHiden) {
            if (mInputMethodManager.isActive) {
                val v = activity.window.peekDecorView()
                if (v != null && v.windowToken != null) {
                    mInputMethodManager.hideSoftInputFromWindow(v.windowToken, 0)
                }
            }
        } else {
            mInputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY)
        }
    }

    /**
     * 打卡软键盘
     */
    fun openKeyBord(mEditText: EditText?, mContext: Context) {
        val imm = mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN)
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }

    /**
     * 关闭软键盘
     */
    fun closeKeybord(mEditText: EditText, mContext: Context) {
        val imm = mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(mEditText.windowToken, 0)
    }

    /**
     * 打开键盘
     *
     * @param context the context
     */
    fun showSoftInput(context: Context) {
        val inputMethodManager =
            context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    /**
     * 关闭键盘事件.
     */
    fun closeSoftInput(context: Activity) {
        val inputMethodManager =
            context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (inputMethodManager != null && (context as Activity).currentFocus != null) {
            inputMethodManager.hideSoftInputFromWindow(
                context
                    .currentFocus!!.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }
}